import {
  app,
  shell,
  BrowserWindow,
  globalShortcut,
  ipcMain,
  Tray,
  Menu
} from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'

import icon from '../../resources/icon.png?asset'
import {
  LOGIN_WIDTH,
  LOGIN_HEIGHT,
  REGISTER_HEIGHT,
  WINDOW_WIDTH,
  WINDOW_HEIGHT
} from './libs/constant'

// import { setUserId, setUserData, setUser } from './libs/store'

const NODE_ENV = process.env.NODE_ENV // 获取环境变量

function createWindow(): void {
  const mainWindow = new BrowserWindow({
    width: LOGIN_WIDTH,
    height: LOGIN_HEIGHT,
    show: false,
    icon,
    alwaysOnTop: true,
    resizable: false,
    frame: false,
    roundedCorners: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  //打开控制台
  if (NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools()
  }
  // 设置刷新快捷键
  if (NODE_ENV === 'development') {
    globalShortcut.register('f5', () => {
      mainWindow.webContents.reload()
    })
  }

  // 设置托盘图标
  const tray = new Tray(icon)
  const contextMeun = [
    {
      label: '退出boyiChat',
      click: () => {
        app.quit()
      }
    }
  ]
  const menu = Menu.buildFromTemplate(contextMeun)
  tray.setContextMenu(menu)
  tray.on('click', function () {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
  })

  // 监听窗口大小的改变
  ipcMain.on('changeWindowSize', (_, data) => {
    mainWindow.setResizable(true)
    // 登录注册的窗口大小
    if (data.isLogin && data.loginOrResgist) {
      mainWindow.setMinimumSize(LOGIN_WIDTH, LOGIN_HEIGHT)
      mainWindow.setSize(LOGIN_WIDTH, LOGIN_HEIGHT)
      mainWindow.setResizable(false)
    }
    if (!data.isLogin && data.loginOrResgist) {
      mainWindow.setSize(LOGIN_WIDTH, REGISTER_HEIGHT)
      mainWindow.setResizable(false)
    }
    // 主页面的窗口大小
    if (data.chat && !data.loginOrResgist) {
      mainWindow.setSize(WINDOW_WIDTH, WINDOW_HEIGHT)
      // 限制最小值
      mainWindow.setMinimumSize(700, 500)
    }
  })

  // 将用户信息保存到主线车中
  ipcMain.on('setUserInfo', (_, data) => {
    // 在显示中显示用用图标
    contextMeun.unshift({
      label: data.username,
      click: () => {}
    })
    tray.setContextMenu(Menu.buildFromTemplate(contextMeun))
  })

  // 监听窗口的设置
  ipcMain.on('setBar', (_, data) => {
    if (data.active === 'top') {
      data.data
        ? mainWindow.setAlwaysOnTop(true)
        : mainWindow.setAlwaysOnTop(false)
    } else if (data.active === 'reduce') {
      mainWindow.minimize()
    } else if (data.active === 'extend') {
      data.data ? mainWindow.maximize() : mainWindow.unmaximize()
    } else {
      if (data.data) {
        mainWindow.hide()
      } else {
        mainWindow.close()
      }
    }
  })
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
